//
//  UIFlowLightView.swift
//  TTCOM-iOS
//
//  Created by Toj on 11/25/22.
//

import UIKit

private let kFlowLightAnimationKey = "kFlowLightAnimationKey"

/* 带有流光效果View */
public class UIFlowLightView: UIView {
    
    public var color = UIColor.white
    public var repeatCount = MAXFLOAT
    
    /** 效果持续时间 */
    public var duration = CGFloat.zero
    /** 效果间隔时间 */
    public var timeInterval = TimeInterval.zero
    
    private var isAnimating = false
    private weak var gradientLayer: CALayer?
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        isUserInteractionEnabled = false
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

public extension UIFlowLightView {
    
    func startAnimation() {
        guard !isAnimating else { return }
        isAnimating = true
        
        let gLayer = CAGradientLayer()
        
        let middleColor = color.tt_alpha(0.4).cgColor
        let fadeRef = color.tt_alpha(0).cgColor
        gLayer.colors = [fadeRef, middleColor, fadeRef]
        gLayer.locations = [0.6, 0.99, 0.99]
        gLayer.startPoint = CGPoint(x: 0, y: 0)
        gLayer.endPoint = CGPoint(x: 1, y: 0.06)
        
        var rect = bounds
        rect.size.width = bounds.width + 100
        gLayer.frame = rect;
        layer.addSublayer(gLayer)
        gradientLayer = gLayer
        
        let startX = -gLayer.frame.size.width
        let endX = 100
        
        let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
        animation.delegate = self
        let duration_ = duration > 0 ? duration : 1
        let interval_ = timeInterval > 0 ? timeInterval : 1
        
        let durationKeyTimes = duration_ / (duration_ + interval_)
        animation.values = [startX, endX, endX]
        animation.duration = duration_ + interval_
        animation.keyTimes = [0, NSNumber(value: durationKeyTimes), 1]
        animation.repeatCount = repeatCount
        animation.isRemovedOnCompletion = false
        animation.fillMode = .forwards
        gLayer.add(animation, forKey: kFlowLightAnimationKey)
    }
    
    func stopFlowLightAnimation() {
        isAnimating = false
        gradientLayer?.removeAnimation(forKey: kFlowLightAnimationKey)
        gradientLayer?.removeFromSuperlayer()
    }
}

extension UIFlowLightView: CAAnimationDelegate {
    
    public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        stopFlowLightAnimation()
    }
}
